package com.wq.sort;

/**
 * @Author: wangqiang20995
 * @Date:2019/2/28
 * @Description:
 * @Resource:
 */
public class BubboSort extends BaseSort {

    public BubboSort(int size) {
        super(size);
    }


    public void sortCommon() {
        int[] data = array;

        for (int i = 0; i < data.length - 1; i++) {
            for (int j = 1; j < data.length - i; j++) {
                if (data[j - 1] > data[j]) {
                    int temp = data[j - 1];
                    data[j - 1] = data[j];
                    data[j] = temp;
                }
            }
        }
    }

    public void sortExchange() {
        int[] data = array;
        for (int i = 0; i < data.length - 1; i++) {
            boolean exchange = false;
            for (int j = 1; j < data.length - i; j++) {
                if (data[j - 1] > data[j]) {
                    int temp = data[j - 1];
                    data[j - 1] = data[j];
                    data[j] = temp;

                    if (!exchange)
                        exchange = true;
                }
            }

            if (!exchange)
                break;
        }
    }

    public void sortPosition() {
        int[] data = array;
        int endPosition = array.length - 1;//暂时记录为最后一个元素的下标

        while (endPosition > 0) {
            int position = 1;//记录上一次循环中，最后一个需要排序的元素的下标

            for (int j = 1; j <= endPosition; j++) {
                if (data[j - 1] > data[j]) {
                    int temp = data[j - 1];
                    data[j - 1] = data[j];
                    data[j] = temp;

                    position = j;
                }
            }

            endPosition = position - 1;
        }
    }

    public void sortHighAndLow() {
        int[] data = array;
        int low = 0;
        int high = data.length - 1;

        while (low < high) {

            for (int i = low + 1; i <= high; i++) {
                if (data[i - 1] > data[i]) {
                    int temp = data[i - 1];
                    data[i - 1] = data[i];
                    data[i] = temp;
                }
            }

            --high;

            for (int i = high; i > low; i--) {
                if (data[i] < data[i - 1]) {
                    int temp = data[i - 1];
                    data[i - 1] = data[i];
                    data[i] = temp;
                }
            }

            ++low;
        }
    }

    public static void main(String args[]) {
        BubboSort bubboSort = new BubboSort(100000);
        long start = System.currentTimeMillis();
//        bubboSort.sortHighAndLow();
        bubboSort.sortPosition();
        long end = System.currentTimeMillis();
        bubboSort.printArray(true);
        System.out.println("cost:" + (end - start));
    }
}
